package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {


    @Autowired
    private ItemMapper mapper;

    /**
     * 根据分页查询数据
     * @param page 当前页
     * @param size  每页显示条数
     * @return
     */
    @Override
    public PageDTO<Item> list(Integer page, Integer size) {

        IPage<Item> p = new Page<>(page,size);

        mapper.selectPage(p, null);

        List<Item> list = p.getRecords();   //当前页面数据

        long total = p.getTotal();  //总记录数

        PageDTO<Item> pageDTO = new PageDTO<>();

        pageDTO.setTotal(total);

        pageDTO.setList(list);

        return pageDTO;

    }

    /**
     * 根据商品id及状态设置上架或下架
     * @param id
     * @param status
     */
    @Override
    public void upOrDown(Long id, Integer status) {

        //要修改的值
        Item item = new Item();

        item.setStatus(status);

        //更新条件
        LambdaQueryWrapper<Item> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Item::getId, id);

        mapper.update(item, wrapper);

    }

    /**
     * 根据id删除指定商品
     * @param id
     */
    @Override
    public void delete(Long id) {

        mapper.deleteById(id);
    }

    /**
     * 插入一条商品
     * @param item
     */
    @Override
    public void addItem(Item item) {

        Item build = Item.builder().id(item.getId()).name(item.getName())
                .price(item.getPrice())
                .stock(item.getStock())
                .image(item.getImage())
                .category(item.getCategory())
                .brand(item.getBrand())
                .spec(item.getSpec())
                .sold(item.getSold())
                .status(1)
                .isAD(item.getIsAD())
                .createTime(new Date())
                .build();

        mapper.insert(build);
    }

    @Override
    public Item findItemById(Long id) {

        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("id", id);

        List<Item> items = mapper.selectList(queryWrapper);

        Item item = items.get(0);

        return item;
    }
}
